package com.example.zhihuhelpapp.mvp;

import android.icu.lang.UScript;
import android.text.TextUtils;
import android.util.Log;

import com.example.zhihuhelpapp.api.MySubscribe;
import com.example.zhihuhelpapp.api.RetrofitManager;
import com.example.zhihuhelpapp.api.mvp.RxPresenter;
import com.example.zhihuhelpapp.bean.JDOrderResult;
import com.example.zhihuhelpapp.mvp.contract.IJongDongApiContract;
import com.example.zhihuhelpapp.utils.CoreConstant;
import com.example.zhihuhelpapp.utils.FormatUtils;
import com.example.zhihuhelpapp.utils.LogUtils;
import com.example.zhihuhelpapp.utils.MD5;
import com.example.zhihuhelpapp.utils.Methods;
import com.example.zhihuhelpapp.utils.SpUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class JingDongApiPresenter extends RxPresenter<IJongDongApiContract.IView> implements IJongDongApiContract.IPresenter {
    public void getOrderList(long time) {
        // 获取最近一个小时内是否有订单
        String appKey = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_JD_APP_KEY, "");
        String appSecret = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_JD_APP_SECRET, "");

        Map<String, String> orderReq = new HashMap<>();

        String currentTime = FormatUtils.longToDateCommon(time, FormatUtils.format_);
        String lastHourTime = FormatUtils.longToDateCommon(time - FormatUtils.anHour - 1000, FormatUtils.format_);

        orderReq.put("pageIndex", "1");
        orderReq.put("pageSize", "20");
        orderReq.put("type", "1");
        orderReq.put("startTime", lastHourTime);
        orderReq.put("endTime", currentTime);

        String orderReqJson;

        JSONObject orderReqJsonObject = new JSONObject();
        try {
            orderReqJsonObject.put("orderReq", new JSONObject(orderReq));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        orderReqJson = orderReqJsonObject.toString();

        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("format", "json");
        params.put("sign_method", "md5");
        params.put("v", "1.0");
        params.put("method", Methods.get_order_info);
        params.put("param_json", orderReqJson);
        params.put("timestamp", FormatUtils.getDetailTime());

        StringBuilder result = new StringBuilder();
        result.append(appSecret);

        // 排序
        Set<String> keySet = params.keySet();
        List<String> keyList = new ArrayList<>(keySet);
        Collections.sort(keyList);

        Map<String, String> resultParams = new HashMap<>();
        for (String key : keyList) {
            result.append(key).append(params.get(key));
            resultParams.put(key, params.get(key));
        }

        result.append(appSecret);
        String md5 = MD5.md5(result.toString());
        resultParams.put("sign", md5.toUpperCase());
        keyList.add("sign");

        StringBuilder paramsStr = new StringBuilder();
        paramsStr.append(CoreConstant.JD_SERVER_URL);
        paramsStr.append("?");

        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            paramsStr.append(key).append("=").append(resultParams.get(key));
            if (i != keyList.size() - 1) {
                paramsStr.append("&");
            }
        }

        LogUtils.i("请求地址：" + paramsStr);

        RetrofitManager.getInstance()
                .apiService()
                .getJongDongOrderInfo(paramsStr.toString())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MySubscribe<JDOrderResult>() {
                    @Override
                    public void onNext(JDOrderResult resultBean) {
                        mView.hideProgress();
                        JDOrderResult.JdUnionOpenOrderRowQueryResponseBean queryResponse = resultBean.getJd_union_open_order_row_query_response();
                        boolean haOrder = false;
                        if (queryResponse != null) {
                            if (queryResponse.isSuccess()) {
                                String result = queryResponse.getResult();
                                if (!TextUtils.isEmpty(result)) {
                                    JDOrderResult.JdUnionOpenOrderRowQueryResponseBean.JDOrderBean jdOrderBean = new Gson().fromJson(result, JDOrderResult.JdUnionOpenOrderRowQueryResponseBean.JDOrderBean.class);
                                    if (jdOrderBean != null) {
                                        if (jdOrderBean.isSuccess()) {
                                            // 请求成功，并且又订单
                                            List<JDOrderResult.JdUnionOpenOrderRowQueryResponseBean.JDOrderBean.DataBean> data = jdOrderBean.getData();
                                            if (data != null && data.size() > 0) {
                                                haOrder = true;
                                                mView.onGetOrderList(data);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (!haOrder) {
                            mView.onNoOrder();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mView.hideProgress();
                        LogUtils.i("调取京东接口异常：" + e.getMessage());
                    }
                });

    }

}
